home *** CD-ROM | disk | FTP | other *** search
/ Developer CD Series 1999 May: Tool Chest / Developer CD Series Tool Chest (Apple Computer)(May 1999).iso / Tool Chest / Development Kits / MPW etc / MPW-GM / MPW / Examples / CExamples / Sample.c < prev    next >
Encoding:
C/C++ Source or Header  |  1998-12-03  |  30.2 KB  |  870 lines  |  [TEXT/MPS ]

  1. /*------------------------------------------------------------------------------
  2. #
  3. #    Apple Macintosh Developer Technical Support
  4. #
  5. #    MultiFinder-Aware Simple Sample Application
  6. #
  7. #    Sample
  8. #
  9. #    Sample.c    -    C Source
  10. #
  11. #    Copyright © 1989-1991, 1994-95 Apple Computer, Inc.
  12. #    All rights reserved.
  13. #
  14. #    Versions:    
  15. #                1.00                08/88
  16. #                1.01                11/88
  17. #                1.02                04/89
  18. #                1.03                06/89
  19. #                1.04                04/91    Updated for MPW 3.2
  20. #                1.05                03/94    Updated for Universal Includes
  21. #
  22. #    Components:
  23. #                Sample.c            Feb.  1, 1990
  24. #                Sample.r            Feb.  1, 1990
  25. #                Sample.h            Feb.  1, 1990
  26. #                Sample.make            Feb.  1, 1990
  27. #
  28. #    Sample is an example application that demonstrates how to
  29. #    initialize the commonly used toolbox managers, operate 
  30. #    successfully under MultiFinder, handle desk accessories, 
  31. #    and create, grow, and zoom windows.
  32. #
  33. #    It does not by any means demonstrate all the techniques 
  34. #    you need for a large application. In particular, Sample 
  35. #    does not cover exception handling, multiple windows/documents, 
  36. #    sophisticated memory management, printing, or undo. All of 
  37. #    these are vital parts of a normal full-sized application.
  38. #
  39. #    This application is an example of the form of a Macintosh 
  40. #    application; it is NOT a template. It is NOT intended to be 
  41. #    used as a foundation for the next world-class, best-selling, 
  42. #    600K application. A stick figure drawing of the human body may 
  43. #    be a good example of the form for a painting, but that does not 
  44. #    mean it should be used as the basis for the next Mona Lisa.
  45. #
  46. #    We recommend that you review this program or TESample before 
  47. #    beginning a new application.
  48. #
  49. ------------------------------------------------------------------------------*/
  50.  
  51.  
  52. /* Segmentation strategy:
  53.  
  54.    This program consists of three segments. Main contains most of the code,
  55.    including the MPW libraries, and the main program. Initialize contains
  56.    code that is only used once, during startup, and can be unloaded after the
  57.    program starts. %A5Init is automatically created by the Linker to initialize
  58.    globals for the MPW libraries and is unloaded right away. */
  59.  
  60.  
  61. /* SetPort strategy:
  62.  
  63.    Toolbox routines do not change the current port. In spite of this, in this
  64.    program we use a strategy of calling SetPort whenever we want to draw or
  65.    make calls which depend on the current port. This makes us less vulnerable
  66.    to bugs in other software which might alter the current port (such as the
  67.    bug (feature?) in many desk accessories which change the port on OpenDeskAcc).
  68.    Hopefully, this also makes the routines from this program more self-contained,
  69.    since they don't depend on the current port setting. */
  70.  
  71.  
  72. #include <Limits.h>
  73. #include <Types.h>
  74. #include <Resources.h>
  75. #include <QuickDraw.h>
  76. #include <Fonts.h>
  77. #include <Events.h>
  78. #include <Windows.h>
  79. #include <Menus.h>
  80. #include <TextEdit.h>
  81. #include <Dialogs.h>
  82. #include <Menus.h>
  83. #include <Devices.h>
  84. #include <ToolUtils.h>
  85. #include <Memory.h>
  86. #include <Processes.h>
  87. #include <SegLoad.h>
  88. #include <Files.h>
  89. #include <OSUtils.h>
  90. #include <DiskInit.h>
  91. #include <Packages.h>
  92. #include <Traps.h>
  93.  
  94. #include "Sample.h"        /* bring in all the #defines for Sample */
  95.  
  96. /* The "g" prefix is used to emphasize that a variable is global. */
  97.  
  98. /* GMac is used to hold the result of a SysEnvirons call. This makes
  99.    it convenient for any routine to check the environment. */
  100. SysEnvRec    gMac;                /* set up by Initialize */
  101.  
  102. /* GHasWaitNextEvent is set at startup, and tells whether the WaitNextEvent
  103.    trap is available. If it is false, we know that we must call GetNextEvent. */
  104. Boolean        gHasWaitNextEvent;    /* set up by Initialize */
  105.  
  106. /* GInBackground is maintained by our osEvent handling routines. Any part of
  107.    the program can check it to find out if it is currently in the background. */
  108. Boolean        gInBackground;        /* maintained by Initialize and DoEvent */
  109.  
  110. /* The qd global has been removed from the libraries */
  111. QDGlobals qd;
  112.  
  113. /* The following globals are the state of the window. If we supported more than
  114.    one window, they would be attatched to each document, rather than globals. */
  115.  
  116. /* GStopped tells whether the stop light is currently on stop or go. */
  117. Boolean        gStopped;            /* maintained by Initialize and SetLight */
  118.  
  119. /* GStopRect and gGoRect are the rectangles of the two stop lights in the window. */
  120. Rect        gStopRect;            /* set up by Initialize */
  121. Rect        gGoRect;            /* set up by Initialize */
  122.  
  123.  
  124. /* Here are declarations for all of the C routines. In MPW 3.0 and later we can use
  125.    actual prototypes for parameter type checking. */
  126. void EventLoop( void );
  127. void DoEvent( EventRecord *event );
  128. void AdjustCursor( Point mouse, RgnHandle region );
  129. void GetGlobalMouse( Point *mouse );
  130. void DoUpdate( WindowPtr window );
  131. void DoActivate( WindowPtr window, Boolean becomingActive );
  132. void DoContentClick( WindowPtr window );
  133. void DrawWindow( WindowPtr window );
  134. void AdjustMenus( void );
  135. void DoMenuCommand( long menuResult );
  136. void SetLight( WindowPtr window, Boolean newStopped );
  137. Boolean DoCloseWindow( WindowPtr window );
  138. void Terminate( void );
  139. void Initialize( void );
  140. Boolean GoGetRect( short rectID, Rect *theRect );
  141. void ForceEnvirons( void );
  142. Boolean IsAppWindow( WindowPtr window );
  143. Boolean IsDAWindow( WindowPtr window );
  144. Boolean TrapAvailable( short tNumber, TrapType tType );
  145. void AlertUser( void );
  146.  
  147.  
  148. /* Define HiWrd and LoWrd macros for efficiency. */
  149. #define HiWrd(aLong)    (((aLong) >> 16) & 0xFFFF)
  150. #define LoWrd(aLong)    ((aLong) & 0xFFFF)
  151.  
  152. /* Define TopLeft and BotRight macros for convenience. Notice the implicit
  153.    dependency on the ordering of fields within a Rect */
  154. #define TopLeft(aRect)    (* (Point *) &(aRect).top)
  155. #define BotRight(aRect)    (* (Point *) &(aRect).bottom)
  156.  
  157.  
  158. extern void _DataInit(void);
  159.  
  160. /* This routine is part of the MPW runtime library. This external
  161.    reference to it is done so that we can unload its segment, %A5Init. */
  162.  
  163.  
  164. #pragma segment Main
  165. main(void)
  166. {
  167.  
  168.     UnloadSeg((Ptr) _DataInit);        /* note that _DataInit must not be in Main! */
  169.     
  170.     /* 1.01 - call to ForceEnvirons removed */
  171.     
  172.     /*    If you have stack requirements that differ from the default,
  173.         then you could use SetApplLimit to increase StackSpace at 
  174.         this point, before calling MaxApplZone. */
  175.     MaxApplZone();                    /* expand the heap so code segments load at the top */
  176.  
  177.     Initialize();                    /* initialize the program */
  178.     
  179.     UnloadSeg((Ptr) Initialize);    /* note that Initialize must not be in Main! */
  180.  
  181.     EventLoop();                    /* call the main event loop */
  182. }
  183.  
  184.  
  185. /*    Get events forever, and handle them by calling DoEvent.
  186.     Get the events by calling WaitNextEvent, if it's available, otherwise
  187.     by calling GetNextEvent. Also call AdjustCursor each time through the loop. */
  188.  
  189. #pragma segment Main
  190. void EventLoop(void)
  191. {
  192.     RgnHandle    cursorRgn;
  193.     Boolean        gotEvent;
  194.     EventRecord    event;
  195.     Point        mouse;
  196.  
  197.     cursorRgn = NewRgn();            /* we’ll pass WNE an empty region the 1st time thru */
  198.     do {
  199.         /* use WNE if it is available */
  200.         if ( gHasWaitNextEvent ) {
  201.             GetGlobalMouse(&mouse);
  202.             AdjustCursor(mouse, cursorRgn);
  203.             gotEvent = WaitNextEvent(everyEvent, &event, LONG_MAX, cursorRgn);
  204.         }
  205.         else {
  206.             SystemTask();
  207.             gotEvent = GetNextEvent(everyEvent, &event);
  208.         }
  209.         if ( gotEvent ) {
  210.             /* make sure we have the right cursor before handling the event */
  211.             AdjustCursor(event.where, cursorRgn);
  212.             DoEvent(&event);
  213.         }
  214.         /*    If you are using modeless dialogs that have editText items,
  215.             you will want to call IsDialogEvent to give the caret a chance
  216.             to blink, even if WNE/GNE returned FALSE. However, check FrontWindow
  217.             for a non-NIL value before calling IsDialogEvent. */
  218.     } while ( true );    /* loop forever; we quit via ExitToShell */
  219. } /*EventLoop*/
  220.  
  221.  
  222. /* Do the right thing for an event. Determine what kind of event it is, and call
  223.  the appropriate routines. */
  224.  
  225. #pragma segment Main
  226. void DoEvent(EventRecord *event)
  227. {
  228.     short        part, err;
  229.     WindowPtr    window;
  230.     Boolean        hit;
  231.     char        key;
  232.     Point        aPoint;
  233.  
  234.     switch ( event->what ) {
  235.         case mouseDown:
  236.             part = FindWindow(event->where, &window);
  237.             switch ( part ) {
  238.                 case inMenuBar:                /* process a mouse menu command (if any) */
  239.                     AdjustMenus();
  240.                     DoMenuCommand(MenuSelect(event->where));
  241.                     break;
  242.                 case inSysWindow:            /* let the system handle the mouseDown */
  243.                     SystemClick(event, window);
  244.                     break;
  245.                 case inContent:
  246.                     if ( window != FrontWindow() ) {
  247.                         SelectWindow(window);
  248.                         /*DoEvent(event);*/    /* use this line for "do first click" */
  249.                     } else
  250.                         DoContentClick(window);
  251.                     break;
  252.                 case inDrag:                /* pass screenBits.bounds to get all gDevices */
  253.                     DragWindow(window, event->where, &qd.screenBits.bounds);
  254.                     break;
  255.                 case inGrow:
  256.                     break;
  257.                 case inZoomIn:
  258.                 case inZoomOut:
  259.                     hit = TrackBox(window, event->where, part);
  260.                     if ( hit ) {
  261.                         SetPort(window);                /* the window must be the current port... */
  262.                         EraseRect(&window->portRect);    /* because of a bug in ZoomWindow */
  263.                         ZoomWindow(window, part, true);    /* note that we invalidate and erase... */
  264.                         InvalRect(&window->portRect);    /* to make things look better on-screen */
  265.                     }
  266.                     break;
  267.             }
  268.             break;
  269.         case keyDown:
  270.         case autoKey:                        /* check for menukey equivalents */
  271.             key = event->message & charCodeMask;
  272.             if ( event->modifiers & cmdKey )            /* Command key down */
  273.                 if ( event->what == keyDown ) {
  274.                     AdjustMenus();                        /* enable/disable/check menu items properly */
  275.                     DoMenuCommand(MenuKey(key));
  276.                 }
  277.             break;
  278.         case activateEvt:
  279.             DoActivate((WindowPtr) event->message, (event->modifiers & activeFlag) != 0);
  280.             break;
  281.         case updateEvt:
  282.             DoUpdate((WindowPtr) event->message);
  283.             break;
  284.         /*    1.01 - It is not a bad idea to at least call DIBadMount in response
  285.             to a diskEvt, so that the user can format a floppy. */
  286.         case diskEvt:
  287.             if ( HiWord(event->message) != noErr ) {
  288.                 SetPt(&aPoint, kDILeft, kDITop);
  289.                 err = DIBadMount(aPoint, event->message);
  290.             }
  291.             break;
  292.         case kOSEvent:
  293.         /*    1.02 - must BitAND with 0x0FF to get only low byte */
  294.             switch ((event->message >> 24) & 0x0FF) {        /* high byte of message */
  295.                 case kSuspendResumeMessage:        /* suspend/resume is also an activate/deactivate */
  296.                     gInBackground = (event->message & kResumeMask) == 0;
  297.                     DoActivate(FrontWindow(), !gInBackground);
  298.                     break;
  299.             }
  300.             break;
  301.     }
  302. } /*DoEvent*/
  303.  
  304.  
  305. /*    Change the cursor's shape, depending on its position. This also calculates the region
  306.     where the current cursor resides (for WaitNextEvent). If the mouse is ever outside of
  307.     that region, an event would be generated, causing this routine to be called,
  308.     allowing us to change the region to the region the mouse is currently in. If
  309.     there is more to the event than just “the mouse moved”, we get called before the
  310.     event is processed to make sure the cursor is the right one. In any (ahem) event,
  311.     this is called again before we     fall back into WNE. */
  312.  
  313. #pragma segment Main
  314. void AdjustCursor(Point    mouse, RgnHandle region)
  315. {
  316.     WindowPtr    window;
  317.     RgnHandle    arrowRgn;
  318.     RgnHandle    plusRgn;
  319.     Rect        globalPortRect;
  320.  
  321.     window = FrontWindow();    /* we only adjust the cursor when we are in front */
  322.     if ( (! gInBackground) && (! IsDAWindow(window)) ) {
  323.         /* calculate regions for different cursor shapes */
  324.         arrowRgn = NewRgn();
  325.         plusRgn = NewRgn();
  326.  
  327.         /* start with a big, big rectangular region */
  328.         SetRectRgn(arrowRgn, kExtremeNeg, kExtremeNeg, kExtremePos, kExtremePos);
  329.  
  330.         /* calculate plusRgn */
  331.         if ( IsAppWindow(window) ) {
  332.             SetPort(window);    /* make a global version of the viewRect */
  333.             SetOrigin(-window->portBits.bounds.left, -window->portBits.bounds.top);
  334.             globalPortRect = window->portRect;
  335.             RectRgn(plusRgn, &globalPortRect);
  336.             SectRgn(plusRgn, window->visRgn, plusRgn);
  337.             SetOrigin(0, 0);
  338.         }
  339.  
  340.         /* subtract other regions from arrowRgn */
  341.         DiffRgn(arrowRgn, plusRgn, arrowRgn);
  342.  
  343.         /* change the cursor and the region parameter */
  344.         if ( PtInRgn(mouse, plusRgn) ) {
  345.             SetCursor(*GetCursor(plusCursor));
  346.             CopyRgn(plusRgn, region);
  347.         } else {
  348.             SetCursor(&qd.arrow);
  349.             CopyRgn(arrowRgn, region);
  350.         }
  351.  
  352.         /* get rid of our local regions */
  353.         DisposeRgn(arrowRgn);
  354.         DisposeRgn(plusRgn);
  355.     }
  356. } /*AdjustCursor*/
  357.  
  358.  
  359. /*    Get the global coordinates of the mouse. When you call OSEventAvail
  360.     it will return either a pending event or a null event. In either case,
  361.     the where field of the event record will contain the current position
  362.     of the mouse in global coordinates and the modifiers field will reflect
  363.     the current state of the modifiers. Another way to get the global
  364.     coordinates is to call GetMouse and LocalToGlobal, but that requires
  365.     being sure that thePort is set to a valid port. */
  366.  
  367. #pragma segment Main
  368. void GetGlobalMouse(Point *mouse)
  369. {
  370.     EventRecord    event;
  371.     
  372.     OSEventAvail(kNoEvents, &event);    /* we aren't interested in any events */
  373.     *mouse = event.where;                /* just the mouse position */
  374. } /*GetGlobalMouse*/
  375.  
  376.  
  377. /*    This is called when an update event is received for a window.
  378.     It calls DrawWindow to draw the contents of an application window.
  379.     As an effeciency measure that does not have to be followed, it
  380.     calls the drawing routine only if the visRgn is non-empty. This
  381.     will handle situations where calculations for drawing or drawing
  382.     itself is very time-consuming. */
  383.  
  384. #pragma segment Main
  385. void DoUpdate(WindowPtr    window)
  386. {
  387.     if ( IsAppWindow(window) ) {
  388.         BeginUpdate(window);                /* this sets up the visRgn */
  389.         if ( ! EmptyRgn(window->visRgn) )    /* draw if updating needs to be done */
  390.             DrawWindow(window);
  391.         EndUpdate(window);
  392.     }
  393. } /*DoUpdate*/
  394.  
  395.  
  396. /*    This is called when a window is activated or deactivated.
  397.     In Sample, the Window Manager's handling of activate and
  398.     deactivate events is sufficient. Other applications may have
  399.     TextEdit records, controls, lists, etc., to activate/deactivate. */
  400.  
  401. #pragma segment Main
  402. void DoActivate(WindowPtr window, Boolean becomingActive)
  403. {
  404.     if ( IsAppWindow(window) ) {
  405.         if ( becomingActive )
  406.             /* do whatever you need to at activation */ ;
  407.         else
  408.             /* do whatever you need to at deactivation */ ;
  409.     }
  410. } /*DoActivate*/
  411.  
  412.  
  413. /*    This is called when a mouse-down event occurs in the content of a window.
  414.     Other applications might want to call FindControl, TEClick, etc., to
  415.     further process the click. */
  416.  
  417. #pragma segment Main
  418. void DoContentClick(WindowPtr window)
  419. {
  420.     SetLight(window, ! gStopped);
  421. } /*DoContentClick*/
  422.  
  423.  
  424. /* Draw the contents of the application window. We do some drawing in color, using
  425.    Classic QuickDraw's color capabilities. This will be black and white on old
  426.    machines, but color on color machines. At this point, the window’s visRgn
  427.    is set to allow drawing only where it needs to be done. */
  428.  
  429. #pragma segment Main
  430. void DrawWindow(WindowPtr window)
  431. {
  432.     SetPort(window);
  433.  
  434.     EraseRect(&window->portRect);    /* clear out any garbage that may linger */
  435.     if ( gStopped )                    /* draw a red (or white) stop light */
  436.         ForeColor(redColor);
  437.     else
  438.         ForeColor(whiteColor);
  439.     PaintOval(&gStopRect);
  440.     ForeColor(blackColor);
  441.     FrameOval(&gStopRect);
  442.     if ( ! gStopped )                /* draw a green (or white) go light */
  443.         ForeColor(greenColor);
  444.     else
  445.         ForeColor(whiteColor);
  446.     PaintOval(&gGoRect);
  447.     ForeColor(blackColor);
  448.     FrameOval(&gGoRect);
  449. } /*DrawWindow*/
  450.  
  451.  
  452. /*    Enable and disable menus based on the current state.
  453.     The user can only select enabled menu items. We set up all the menu items
  454.     before calling MenuSelect or MenuKey, since these are the only times that
  455.     a menu item can be selected. Note that MenuSelect is also the only time
  456.     the user will see menu items. This approach to deciding what enable/
  457.     disable state a menu item has the advantage of concentrating all
  458.     the decision-making in one routine, as opposed to being spread throughout
  459.     the application. Other application designs may take a different approach
  460.     that is just as valid. */
  461.  
  462. #pragma segment Main
  463. void AdjustMenus(void)
  464. {
  465.     WindowPtr    window;
  466.     MenuHandle    menu;
  467.  
  468.     window = FrontWindow();
  469.  
  470.     menu = GetMenuHandle(mFile);
  471.     if ( IsDAWindow(window) )        /* we can allow desk accessories to be closed from the menu */
  472.         EnableItem(menu, iClose);
  473.     else
  474.         DisableItem(menu, iClose);    /* but not our traffic light window */
  475.  
  476.     menu = GetMenuHandle(mEdit);
  477.     if ( IsDAWindow(window) ) {        /* a desk accessory might need the edit menu… */
  478.         EnableItem(menu, iUndo);
  479.         EnableItem(menu, iCut);
  480.         EnableItem(menu, iCopy);
  481.         EnableItem(menu, iClear);
  482.         EnableItem(menu, iPaste);
  483.     } else {                        /* …but we don’t use it */
  484.         DisableItem(menu, iUndo);
  485.         DisableItem(menu, iCut);
  486.         DisableItem(menu, iCopy);
  487.         DisableItem(menu, iClear);
  488.         DisableItem(menu, iPaste);
  489.     }
  490.  
  491.     menu = GetMenuHandle(mLight);
  492.     if ( IsAppWindow(window) ) {    /* we know that it must be the traffic light */
  493.         EnableItem(menu, iStop);
  494.         EnableItem(menu, iGo);
  495.     } else {
  496.         DisableItem(menu, iStop);
  497.         DisableItem(menu, iGo);
  498.     }
  499.     CheckItem(menu, iStop, gStopped); /* we can also determine check/uncheck state, too */
  500.     CheckItem(menu, iGo, ! gStopped);
  501. } /*AdjustMenus*/
  502.  
  503.  
  504. /*    This is called when an item is chosen from the menu bar (after calling
  505.     MenuSelect or MenuKey). It performs the right operation for each command.
  506.     It is good to have both the result of MenuSelect and MenuKey go to
  507.     one routine like this to keep everything organized. */
  508.  
  509. #pragma segment Main
  510. void DoMenuCommand(long    menuResult)
  511. {
  512.     short        menuID;                /* the resource ID of the selected menu */
  513.     short        menuItem;            /* the item number of the selected menu */
  514.     short        itemHit;
  515.     Str255        daName;
  516.     short        daRefNum;
  517.     Boolean        handledByDA;
  518.  
  519.     menuID = HiWord(menuResult);    /* use macros for efficiency to... */
  520.     menuItem = LoWord(menuResult);    /* get menu item number and menu number */
  521.     switch ( menuID ) {
  522.         case mApple:
  523.             switch ( menuItem ) {
  524.                 case iAbout:        /* bring up alert for About */
  525.                     itemHit = Alert(rAboutAlert, nil);
  526.                     break;
  527.                 default:            /* all non-About items in this menu are DAs */
  528.                     /* type Str255 is an array in MPW 3 */
  529.                     GetMenuItemText(GetMenuHandle(mApple), menuItem, daName);
  530.                     daRefNum = OpenDeskAcc(daName);
  531.                     break;
  532.             }
  533.             break;
  534.         case mFile:
  535.             switch ( menuItem ) {
  536.                 case iClose:
  537.                     DoCloseWindow(FrontWindow());
  538.                     break;
  539.                 case iQuit:
  540.                     Terminate();
  541.                     break;
  542.             }
  543.             break;
  544.         case mEdit:                    /* call SystemEdit for DA editing & MultiFinder */
  545.             handledByDA = SystemEdit(menuItem-1);    /* since we don’t do any Editing */
  546.             break;
  547.         case mLight:
  548.             switch ( menuItem ) {
  549.                 case iStop:
  550.                     SetLight(FrontWindow(), true);
  551.                     break;
  552.                 case iGo:
  553.                     SetLight(FrontWindow(), false);
  554.                     break;
  555.             }
  556.             break;
  557.     }
  558.     HiliteMenu(0);                    /* unhighlight what MenuSelect (or MenuKey) hilited */
  559. } /*DoMenuCommand*/
  560.  
  561.  
  562. /* Change the setting of the light. */
  563.  
  564. #pragma segment Main
  565. void SetLight(WindowPtr    window, Boolean    newStopped)
  566. {
  567.     if ( newStopped != gStopped ) {
  568.         gStopped = newStopped;
  569.         SetPort(window);
  570.         InvalRect(&window->portRect);
  571.     }
  572. } /*SetLight*/
  573.  
  574.  
  575. /* Close a window. This handles desk accessory and application windows. */
  576.  
  577. /*    1.01 - At this point, if there was a document associated with a
  578.     window, you could do any document saving processing if it is 'dirty'.
  579.     DoCloseWindow would return true if the window actually closed, i.e.,
  580.     the user didn’t cancel from a save dialog. This result is handy when
  581.     the user quits an application, but then cancels the save of a document
  582.     associated with a window. */
  583.  
  584. #pragma segment Main
  585. Boolean DoCloseWindow(WindowPtr    window)
  586. {
  587.     if ( IsDAWindow(window) )
  588.         CloseDeskAcc(((WindowPeek) window)->windowKind);
  589.     else if ( IsAppWindow(window) )
  590.         CloseWindow(window);
  591.     return true;
  592. } /*DoCloseWindow*/
  593.  
  594.  
  595. /**************************************************************************************
  596. *** 1.01 DoCloseBehind(window) was removed ***
  597.  
  598.     1.01 - DoCloseBehind was a good idea for closing windows when quitting
  599.     and not having to worry about updating the windows, but it suffered
  600.     from a fatal flaw. If a desk accessory owned two windows, it would
  601.     close both those windows when CloseDeskAcc was called. When DoCloseBehind
  602.     got around to calling DoCloseWindow for that other window that was already
  603.     closed, things would go very poorly. Another option would be to have a
  604.     procedure, GetRearWindow, that would go through the window list and return
  605.     the last window. Instead, we decided to present the standard approach
  606.     of getting and closing FrontWindow until FrontWindow returns NIL. This
  607.     has a potential benefit in that the window whose document needs to be saved
  608.     may be visible since it is the front window, therefore decreasing the
  609.     chance of user confusion. For aesthetic reasons, the windows in the
  610.     application should be checked for updates periodically and have the
  611.     updates serviced.
  612. **************************************************************************************/
  613.  
  614.  
  615. /* Clean up the application and exit. We close all of the windows so that
  616.  they can update their documents, if any. */
  617.  
  618. /*    1.01 - If we find out that a cancel has occurred, we won't exit to the
  619.     shell, but will return instead. */
  620.  
  621. #pragma segment Main
  622. void Terminate(void)
  623. {
  624.     WindowPtr    aWindow;
  625.     Boolean        closed;
  626.     
  627.     closed = true;
  628.     do {
  629.         aWindow = FrontWindow();                /* get the current front window */
  630.         if (aWindow != nil)
  631.             closed = DoCloseWindow(aWindow);    /* close this window */    
  632.     }
  633.     while (closed && (aWindow != nil));
  634.     if (closed)
  635.         ExitToShell();                            /* exit if no cancellation */
  636. } /*Terminate*/
  637.  
  638.  
  639. /*    Set up the whole world, including global variables, Toolbox managers,
  640.     and menus. We also create our one application window at this time.
  641.     Since window storage is non-relocateable, how and when to allocate space
  642.     for windows is very important so that heap fragmentation does not occur.
  643.     Because Sample has only one window and it is only disposed when the application
  644.     quits, we will allocate its space here, before anything that might be a locked
  645.     relocatable object gets into the heap. This way, we can force the storage to be
  646.     in the lowest memory available in the heap. Window storage can differ widely
  647.     amongst applications depending on how many windows are created and disposed. */
  648.  
  649. /*    1.01 - The code that used to be part of ForceEnvirons has been moved into
  650.     this module. If an error is detected, instead of merely doing an ExitToShell,
  651.     which leaves the user without much to go on, we call AlertUser, which puts
  652.     up a simple alert that just says an error occurred and then calls ExitToShell.
  653.     Since there is no other cleanup needed at this point if an error is detected,
  654.     this form of error- handling is acceptable. If more sophisticated error recovery
  655.     is needed, an exception mechanism, such as is provided by Signals, can be used. */
  656.  
  657. #pragma segment Initialize
  658. void Initialize(void)
  659. {
  660.     Handle        menuBar;
  661.     WindowPtr    window;
  662.     long        total, contig;
  663.     EventRecord event;
  664.     short        count;
  665.  
  666.     gInBackground = false;
  667.  
  668.     InitGraf((Ptr) &qd.thePort);
  669.     InitFonts();
  670.     InitWindows();
  671.     InitMenus();
  672.     TEInit();
  673.     InitDialogs(nil);
  674.     InitCursor();
  675.         
  676.     /*    Call MPPOpen and ATPLoad at this point to initialize AppleTalk,
  677.          if you are using it. */
  678.     /*    NOTE -- It is no longer necessary, and actually unhealthy, to check
  679.         PortBUse and SPConfig before opening AppleTalk. The drivers are capable
  680.         of checking for port availability themselves. */
  681.     
  682.     /*    This next bit of code is necessary to allow the default button of our
  683.         alert be outlined.
  684.         1.02 - Changed to call EventAvail so that we don't lose some important
  685.         events. */
  686.      
  687.     for (count = 1; count <= 3; count++)
  688.         EventAvail(everyEvent, &event);
  689.     
  690.     /*    Ignore the error returned from SysEnvirons; even if an error occurred,
  691.         the SysEnvirons glue will fill in the SysEnvRec. You can save a redundant
  692.         call to SysEnvirons by calling it after initializing AppleTalk. */
  693.      
  694.     SysEnvirons(kSysEnvironsVersion, &gMac);
  695.     
  696.     /* Make sure that the machine has at least 128K ROMs. If it doesn't, exit. */
  697.     
  698.     if (gMac.machineType < 0) AlertUser();
  699.         
  700.     /*    1.02 - Move TrapAvailable call to after SysEnvirons so that we can tell
  701.         in TrapAvailable if a tool trap value is out of range. */
  702.         
  703.     gHasWaitNextEvent = TrapAvailable(_WaitNextEvent, ToolTrap);
  704.     
  705.     /*    1.01 - We used to make a check for memory at this point by examining ApplLimit,
  706.         ApplicZone, and StackSpace and comparing that to the minimum size we told
  707.         MultiFinder we needed. This did not work well because it assumed too much about
  708.         the relationship between what we asked MultiFinder for and what we would actually
  709.         get back, as well as how to measure it. Instead, we will use an alternate
  710.         method comprised of two steps. */
  711.      
  712.     /*    It is better to first check the size of the application heap against a value
  713.         that you have determined is the smallest heap the application can reasonably
  714.         work in. This number should be derived by examining the size of the heap that
  715.         is actually provided by MultiFinder when the minimum size requested is used.
  716.         The derivation of the minimum size requested from MultiFinder is described
  717.         in Sample.h. The check should be made because the preferred size can end up
  718.         being set smaller than the minimum size by the user. This extra check acts to
  719.         insure that your application is starting from a solid memory foundation. */
  720.      
  721.     if ((long) GetApplLimit() - (long) ApplicationZone() < kMinHeap) AlertUser();
  722.     
  723.     /*    Next, make sure that enough memory is free for your application to run. It
  724.         is possible for a situation to arise where the heap may have been of required
  725.         size, but a large scrap was loaded which left too little memory. To check for
  726.         this, call PurgeSpace and compare the result with a value that you have determined
  727.         is the minimum amount of free memory your application needs at initialization.
  728.         This number can be derived several different ways. One way that is fairly
  729.         straightforward is to run the application in the minimum size configuration
  730.         as described previously. Call PurgeSpace at initialization and examine the value
  731.         returned. However, you should make sure that this result is not being modified
  732.         by the scrap's presence. You can do that by calling ZeroScrap before calling
  733.         PurgeSpace. Make sure to remove that call before shipping, though. */
  734.     
  735.     /* ZeroScrap(); */
  736.  
  737.     PurgeSpace(&total, &contig);
  738.     if (total < kMinSpace) AlertUser();
  739.  
  740.     /*    The extra benefit to waiting until after the Toolbox Managers have been initialized
  741.         to check memory is that we can now give the user an alert to tell him/her what
  742.         happened. Although it is possible that the memory situation could be worsened by
  743.         displaying an alert, MultiFinder would gracefully exit the application with
  744.         an informative alert if memory became critical. Here we are acting more
  745.         in a preventative manner to avoid future disaster from low-memory problems. */
  746.  
  747.     /*     we will allocate our own window storage instead of letting the Window
  748.         Manager do it because GetNewWindow may load in temp. resources before
  749.         making the NewPtr call, and this can lead to heap fragmentation. */
  750.     window = (WindowPtr) NewPtr(sizeof(WindowRecord));
  751.     if ( window == nil ) AlertUser();
  752.     window = GetNewWindow(rWindow, (Ptr) window, (WindowPtr) -1);
  753.     
  754.     menuBar = GetNewMBar(rMenuBar);            /* read menus into menu bar */
  755.     if ( menuBar == nil ) AlertUser();
  756.     SetMenuBar(menuBar);                    /* install menus */
  757.     DisposeHandle(menuBar);
  758.     AppendResMenu(GetMenuHandle(mApple), 'DRVR');    /* add DA names to Apple menu */
  759.     DrawMenuBar();
  760.     
  761.     gStopped = true;
  762.     
  763.     if ( !GoGetRect(rStopRect, &gStopRect) )
  764.         AlertUser();                        /* the stop light rectangle */
  765.         
  766.     if ( !GoGetRect(rGoRect, &gGoRect) )
  767.         AlertUser();                        /* the go light rectangle */
  768. } /*Initialize*/
  769.  
  770.  
  771. /*    This utility loads the global rectangles that are used by the window
  772.     drawing routines. It shows how the resource manager can be used to hold
  773.     values in a convenient manner. These values are then easily altered without
  774.     having to re-compile the source code. In this particular case, we know
  775.     that this routine is being called at initialization time. Therefore,
  776.     if a failure occurs here, we will assume that the application is in such
  777.     bad shape that we should just exit. Your error handling may differ, but
  778.     the check should still be made. */
  779.     
  780. #pragma segment Initialize
  781. Boolean GoGetRect(short    rectID, Rect *theRect)
  782. {
  783.     Handle        resource;
  784.     
  785.     resource = GetResource('RECT', rectID);
  786.     
  787.     if ( resource != nil ) {
  788.         *theRect = **((Rect**) resource);
  789.         return true;
  790.     }
  791.     else
  792.         return false;
  793. } /* GoGetRect */
  794.  
  795.  
  796. /*    Check to see if a window belongs to the application. If the window pointer
  797.     passed was NIL, then it could not be an application window. WindowKinds
  798.     that are negative belong to the system and windowKinds less than userKind
  799.     are reserved by Apple except for windowKinds equal to dialogKind, which
  800.     mean it is a dialog.
  801.     1.02 - In order to reduce the chance of accidentally treating some window
  802.     as an AppWindow that shouldn't be, we'll only return true if the windowkind
  803.     is userKind. If you add different kinds of windows to Sample you'll need
  804.     to change how this all works. */
  805.  
  806. #pragma segment Main
  807. Boolean IsAppWindow(WindowPtr window)
  808. {
  809.     short        windowKind;
  810.  
  811.     if ( window == nil )
  812.         return false;
  813.     else {    /* application windows have windowKinds = userKind (8) */
  814.         windowKind = ((WindowPeek) window)->windowKind;
  815.         return ( windowKind == userKind );
  816.     }
  817. } /*IsAppWindow*/
  818.  
  819.  
  820. /* Check to see if a window belongs to a desk accessory. */
  821.  
  822. #pragma segment Main
  823. Boolean IsDAWindow(WindowPtr window)
  824. {
  825.     if ( window == nil )
  826.         return false;
  827.     else    /* DA windows have negative windowKinds */
  828.         return ( ((WindowPeek) window)->windowKind < 0 );
  829. } /*IsDAWindow*/
  830.  
  831.  
  832. /*    Check to see if a given trap is implemented. This is only used by the
  833.     Initialize routine in this program, so we put it in the Initialize segment.
  834.     The recommended approach to see if a trap is implemented is to see if
  835.     the address of the trap routine is the same as the address of the
  836.     Unimplemented trap. */
  837. /*    1.02 - Needs to be called after call to SysEnvirons so that it can check
  838.     if a ToolTrap is out of range of a pre-MacII ROM. */
  839.  
  840. #pragma segment Initialize
  841. Boolean TrapAvailable(short    tNumber, TrapType tType)
  842. {
  843.     if ( ( tType == ToolTrap ) &&
  844.         ( gMac.machineType > envMachUnknown ) &&
  845.         ( gMac.machineType < envMacII ) ) {        /* it's a 512KE, Plus, or SE */
  846.         tNumber = tNumber & 0x03FF;
  847.         if ( tNumber > 0x01FF )                    /* which means the tool traps */
  848.             tNumber = _Unimplemented;            /* only go to 0x01FF */
  849.     }
  850.     return NGetTrapAddress(tNumber, tType) != NGetTrapAddress(_Unimplemented, ToolTrap);
  851. } /*TrapAvailable*/
  852.  
  853.  
  854. /*    Display an alert that tells the user an error occurred, then exit the program.
  855.     This routine is used as an ultimate bail-out for serious errors that prohibit
  856.     the continuation of the application. Errors that do not require the termination
  857.     of the application should be handled in a different manner. Error checking and
  858.     reporting has a place even in the simplest application. The error number is used
  859.     to index an 'STR#' resource so that a relevant message can be displayed. */
  860.  
  861. #pragma segment Main
  862. void AlertUser(void)
  863. {
  864.     short        itemHit;
  865.  
  866.     SetCursor(&qd.arrow);
  867.     itemHit = Alert(rUserAlert, nil);
  868.     ExitToShell();
  869. } /* AlertUser */
  870.